<template>
  <div class="retrieve">
    <Header>
      <div slot="title" class="header-title">忘记密码</div>
      <div slot="left" class="header-left">
        <img src="@/assets/index/back.png" alt />
      </div>
    </Header>
    <div class="fenge"></div>
    <div class="PasswordCon" v-if="!validateStatus">
      <van-form :show-error='false' validate-trigger='onSubmit' validate-first @submit="onSubmit" ref="form">
        <van-field
          v-model="phoneNum"
          @blur="blur('phoneNum',phoneNum)"
            @input="change('phoneNum',phoneNum)"
          name="phoneNum"
          label="手机号"
          clearable
          placeholder="请输入手机号码"
          :rules="[
            {
              required: true,
              validator: validatePhone,
              message: (value)=>{
                  if(!value){
                    return '请输入手机号'
                  }
                  if(!this.validatePhone(value)){
                    return '请输入正确的手机号'
                  }
                }
            },
          ]"
        ></van-field>
        <van-field
          v-model="code"
          @blur="blur('codeNum',code)"
            @input="change('codeNum',code)"
          type="text"
          name="code"
          label="验证码"
          clearable
          placeholder="请输入验证码"
          :rules="[
            {
              required: true,
              validator: validateCode,
              message: (value)=>{
                  if(!value){
                    return '请输入验证码'
                  }
                  if(!this.validateCode(value)){
                    return '请输入正确的验证码'
                  }
                }
            },
          ]"
        >
          <template class="password-field" slot="right-icon" name="right-icon">
            <span
              class="password-span"
              @click="getCode('form', 'phoneNum')"
              v-if="!countDown"
              >获取验证码</span
            >
            <span class="password-span" v-else
              >重新获取( {{ restTime }} s)</span
            >
          </template>
        </van-field>
        <van-field
          v-model="passForm.password"
          @blur="blur('password',passForm.password)"
            @input="change('password',passForm.password)"
          type="password"
          name="password"
          label="新密码"
          clearable
          placeholder="请输入密码"
          :rules="[
            {
              required: true,
              validator: validatePass,
              message: (value)=>{
                  if(!value){
                    return '请输入密码'
                  }
                  if(value.length<6){
                    return '长度6-20个字符之间'
                  }
                  if(this._str(value, value[0]) == value.length){
                    return '不能使用同一字符'
                  }
                  if(!this.validatePass(value)){
                    return '非法字符，请使用字母、数字的组合，6-20个字符'
                  }
                },
            },
          ]"
        ></van-field>
        <van-field
          v-model="passForm.again"
          type="password"
          name="again"
          label="确认密码"
           @blur="blur('again',passForm.again)"
            @input="change('again',passForm.again)"
          clearable
          placeholder="请再次输入密码"
          :rules="[
            {
              required: true,
              validator: validateAgain,
              message: '密码输入不一致',
            },
          ]"
        ></van-field>
      </van-form>
      <div>
        <div style="margin: 25px">
          <van-button
            class="setPassButton"
            round
            block
            type="default"
            native-type="submit"
            @click="
              () => {
                this.$refs.form.submit();
              }
            "
            >提交</van-button
          >
        </div>
      </div>
    </div>
    <div class="success" v-else-if="validateStatus">
      <img src="./img/tishi.png" alt="" />
      <p class="p1">恭喜您，密码重新设定成功！</p>
      <p class="p2">3秒后自动跳转至登陆页</p>
      <p class="p3" 
      @click="() => {
                this.$router.push({ path: '/login/sign' });
              }"
      >立即跳转</p>
    </div>
    <Verify
      @success="sliderPassed"
      :captchaType="captchaType"
      :phone="phoneNum"
      :imgSize="{ width: '400px', height: '200px' }"
      ref="captchaVer"
    ></Verify>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import { Form, Field, Button, Divider } from "vant";
import Verify from "./component/verifition/Verify";
import {
  getPhoneCodeAPI,
  validateResetPassAPI,
  resetPasswordAPI,
} from "./api/login";
import { CODE_TYPE, BUSINESS_TYPE, RESET_TIME } from "./utils/constant";
import { cGet, cSet, cRemove } from "./utils/saveMethod";
import {
  warningMessage,
  successMessage,
  errorMessage,
  linkName,
  linkOpen,
} from "./utils/function";
import md5 from "js-md5";
export default {
  components: {
    Header,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Divider.name]: Divider,
    Verify,
  },
  data() {
    return {
      validateStatus: false,
      countDown: false,
      phoneNum: undefined,
      code: "",
      captchaType: "", // 滑块验证码方式
      restTime: RESET_TIME,
      uuid: "",
      timer: null,
      loginLoading: false,
      passForm: {
        password: "",
        again: "",
        token: "",
      },
    };
  },
  methods: {
    blur(type,v){
      let me = this;
      if(v){
        let form = 'form';
        switch (type) {
          case 'password':
            this.$refs[form].validate('password');
            break;
           case 'again':
            this.$refs[form].validate('again');
            break;  
          case 'phoneNum':
            this.$refs[form].validate('phoneNum');
            break;
          case 'codeNum':
            this.$refs[form].validate('code');
            break;    
          default:
            break;
        }
      }
    },
    change(type,v){
      if(v){
        let form = 'form';
        let me = this;
        switch (type) {
         case 'password':
            this.$refs[form].validate('password');
            break;
           case 'again':
            this.$refs[form].validate('again');
            break;  
          case 'phoneNum':
            this.$refs[form].validate('phoneNum');
            break;
          case 'codeNum':
            this.$refs[form].validate('code');
            break;    
          default:
            break;
        }
      }
    },
    _str(value, n){
        var tmp = 0;
        for(var i = 0; i < value.length; i++){
            if(value.charAt(i) == n){    //charAt()方法可返回指定位置的字符
              tmp++;
              console.log(tmp);
            }
        }
        return tmp;    
    }, 
    onSubmit() {
      if (!this.uuid) {
        warningMessage("请先获取验证码");
        return;
      }
      this._validateReset();
    },
    getCode(refName, name) {
      if (!this.phoneNum) {
         warningMessage("请输入手机号");
         return;
      };
      this.$refs[refName].validate(name).then(
        (_) => {
          console.log("打开滑动验证码");
          this.$refs.captchaVer.show();
        },
        (errorMsg) => {
          // warningMessage("手机号输入错误！");
        }
      );
    },
    // 滑块验证码通过，获取短信验证码
    sliderPassed(val) {
      let self = this;

      getPhoneCodeAPI(val).then((res) => {
        if (res.data.code == 0) {
          this.countDown = true;
          this.uuid = res.data.data.uuid;
          let timer = setInterval(() => {
            if (self.restTime == 0) {
              this.countDown = false;
              clearInterval(timer);
              self.restTime = RESET_TIME;
              return;
            } else {
              self.restTime--;
            }
          }, 1000);
        } else {
          warningMessage(res.data.msg);
        }
      });
    },
    // 手机短信验证
    _validateReset() {
      if (this.loginLoading) return;
      this.loginLoading = true;
      let phone = this.phoneNum;
      let code = this.code;
      let data = {
        captchaForm: {
          phone,
          businessType: BUSINESS_TYPE["reset"],
          type: CODE_TYPE["phone"],
          uuid: this.uuid,
          value: code,
        },
      };
      validateResetPassAPI(data).then(
        (res) => {
          console.log(res.data, "jieguo");
          this.loginLoading = false;
          if (res.data.code === 0) {
            this.passForm.token = res.data.data.loginVo.token;
            this.setPassword();
          } else {
            warningMessage(res.data.msg);
          }
        },
        (error) => {
          this.loginLoading = false;
        }
      );
    },
    //重置密码
    setPassword() {
      if (this.loginLoading) return;
      this.loginLoading = true;
      let data = Object.assign({}, this.passForm);
      data.again = md5(this.passForm.again);
      data.password = md5(this.passForm.password);
      resetPasswordAPI(data).then(
        (res) => {
          if (res.data.code === 0) {
            this.validateStatus = true;
            this.timer = setTimeout(() => {
              // successMessage('重置密码成功')
              this.loginLoading = false;
              this.$router.push({ path: '/login/sign' });
            }, 3000);
          } else {
            this.loginLoading = false;
            warningMessage(res.data.msg);
          }
        },
        (error) => {
          this.loginLoading = false;
        }
      );
    },
    validatePhone(value) {
      let reg = /^(13\d|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18\d|19[89])\d{8}$/;
      return reg.test(value);
    },
    validatePass(value) {
      let reg = /^(?=.*\d)[A-Za-z\d]{6,20}$/;
      let flag = reg.test(value);
      if(flag){
        flag = !(this._str(value, value[0]) == value.length)
      }
      return flag
    },
    validateAgain(value) {
      if (value == this.passForm.password) {
        return true;
      } else {
        return false;
      }
    },
    validateCode(value) {
      let reg = /^(\d|\w){4}$/;
      return reg.test(value);
    },
  },
  created() {
    this.captchaType = CODE_TYPE["blockPuzzle"];
  },
  beforeDestroy(){
    clearTimeout(this.timer)
  }
};
</script>

<style lang="scss">
@import "./css/index.scss";
.retrieve {
  width: 100%;
  height: 100%;
  .fenge {
    width: 100%;
    height: 15px;
    background-color: #f3f3f3;
  }
}
.setPassButton {
  background-image: url("./img/denglu-but.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  color: #ffffff;
}
.success {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  img {
    width: 156px;
    height: 125px;
    margin-top: 50px;
  }
  .p1 {
    font-size: 22.5px;
  }
  .p2 {
    font-size: 18px;
  }
  .p3 {
    font-size: 22.5px;
    color: #1e7afc;
    border-bottom: 4px solid #1e7afc;
  }
}
</style>